<template>
  <div>
    <div class="home_filter">
      <el-card>
        <div class="home_filter_content">
          <el-form class="form_container" :model="formData">
            <el-radio-group v-model="formData.tab" style="width: 240px">
              <el-radio-button label="个人" value="0" v-hasPermi="['bms:home:tab_person']" />
              <el-radio-button label="团队" value="1" v-hasPermi="['bms:home:team']" />
            </el-radio-group>
            <el-cascader
              v-model="formData.deptId"
              :props="constantcascaderProps"
              style="width: 450px"
              :options="deptList"
            />
            <el-select v-if="formData.tab === '0'" v-model="formData.userId">
              <el-option
                v-for="option in userList"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
            <el-date-picker
              v-model="formData.dateRange"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :formatter="dateFormatter"
              :default-time="defaultTime"
            />
          </el-form>
        </div>
      </el-card>
    </div>

    <div class="home_price">
      <el-card style="height: 100%">
        <div class="home_price_item">
          <div>{{ homeData?.topStatistics.totalOrders }}个</div>
          <div>
            <div class="home_price_item_price"
              ><span>{{ homeData?.topStatistics.totalAmount }}</span
              ><span> ¥ </span></div
            >
            <div class="home_price_item_name"
              ><span>录单总金额</span>
              <el-tooltip
                class="box-item"
                effect="dark"
                content="录单总金额（包括退件、拒签、不包含审核驳回）"
                placement="top-start"
                ><Icon icon="fa:question-circle" class="ml-5px" /></el-tooltip
            ></div>
          </div>
        </div>
      </el-card>
      <el-card style="height: 100%">
        <div class="home_price_item">
          <div>{{ homeData?.topStatistics.waitingAuditOrders }}个</div>
          <div>
            <div class="home_price_item_price"
              ><span>{{ homeData?.topStatistics.waitingAuditAmount }}</span
              ><span> ¥ </span></div
            >
            <div class="home_price_item_name"
              ><span>待审核订单总金额</span>
              <el-tooltip
                class="box-item"
                effect="dark"
                content="待审核订单总金额（包括退件、拒签、不包含审核驳回）"
                placement="top-start"
                ><Icon icon="fa:question-circle" class="ml-5px" /></el-tooltip
            ></div>
          </div>
        </div>
      </el-card>
      <el-card style="height: 100%">
        <div class="home_price_item">
          <div>{{ homeData?.topStatistics.approvedOrders }}个</div>
          <div>
            <div class="home_price_item_price"
              ><span>{{ homeData?.topStatistics.approvedAmount }}</span
              ><span> ¥ </span></div
            >
            <div class="home_price_item_name"
              ><span>已审核订单金额</span>
              <el-tooltip
                class="box-item"
                effect="dark"
                content="已审核订单金额（待发货+快递中+审核通过暂存的订单金额）"
                placement="top-start"
                ><Icon icon="fa:question-circle" class="ml-5px" /></el-tooltip
            ></div>
          </div>
        </div>
      </el-card>
    </div>

    <div class="home_status">
      <el-card>
        <div class="home_status_item">
          <img src="/src/assets/imgs/home/审核驳回.png" />
          <span>审核驳回</span>
          <span
            >{{ homeData?.orderStatueStatistics.auditRejectedCount }}个/{{
              homeData?.orderStatueStatistics.auditRejectedAmount
            }}¥</span
          >
        </div>
      </el-card>
      <el-card>
        <div class="home_status_item">
          <img src="/src/assets/imgs/home/财务审核.png" />
          <span>财务审核</span>
          <span
            >{{ homeData?.orderStatueStatistics.financeAuditCount }}个/{{
              homeData?.orderStatueStatistics.financeAuditAmount
            }}¥</span
          >
        </div>
      </el-card>
      <el-card>
        <div class="home_status_item">
          <img src="/src/assets/imgs/home/待发货.png" />
          <span>待发货</span>
          <span
            >{{ homeData?.orderStatueStatistics.waitingDeliveryCount }}个/{{
              homeData?.orderStatueStatistics.waitingDeliveryAmount
            }}¥</span
          >
        </div>
      </el-card>
      <el-card>
        <div class="home_status_item">
          <img src="/src/assets/imgs/home/快递中.png" />
          <span>快递中</span>
          <span
            >{{ homeData?.orderStatueStatistics.deliveredCount }}个/{{
              homeData?.orderStatueStatistics.deliveredAmount
            }}¥</span
          >
        </div>
      </el-card>
      <el-card>
        <div class="home_status_item">
          <img src="/src/assets/imgs/home/已签收-物流详情.png" />
          <span>已签收/回款</span>
          <span
            >{{ homeData?.orderStatueStatistics.signedOrReturnedPaymentCount }}个/{{
              homeData?.orderStatueStatistics.signedOrReturnedPaymentAmount
            }}¥</span
          >
        </div>
      </el-card>
      <el-card>
        <div class="home_status_item">
          <img src="/src/assets/imgs/home/存酒.png" />
          <span>存酒</span>
          <span
            >{{ homeData?.orderStatueStatistics.customerDeliveryCount }}个/{{
              homeData?.orderStatueStatistics.customerDeliveryAmount
            }}¥</span
          >
        </div>
      </el-card>
      <el-card>
        <div class="home_status_item">
          <img src="/src/assets/imgs/home/拒签收.png" />
          <span>拒签</span>
          <span
            >{{ homeData?.orderStatueStatistics.rejectedCount }}个/{{
              homeData?.orderStatueStatistics.rejectedAmount
            }}¥</span
          >
        </div>
      </el-card>
      <el-card>
        <div class="home_status_item">
          <img src="/src/assets/imgs/home/退件单.png" />
          <span>退件</span>
          <span
            >{{ homeData?.orderStatueStatistics.returnedCount }}个/{{
              homeData?.orderStatueStatistics.returnedAmount
            }}¥</span
          >
        </div>
      </el-card>
    </div>

    <div class="home_status_level">
      <el-card>
        <template #header>
          <div class="home_card_title">
            <span>录单排名</span>
          </div>
        </template>
        <div class="level_list">
          <div
            class="level_list_item"
            v-for="(item, index) in homeData?.createOrderRank"
            :key="index"
          >
            <span
              :style="{
                background: getColor(index),
                color: index === 3 || index === 4 ? '#303133' : '#fff'
              }"
            >
              {{ index + 1 }}
            </span>

            <span>{{ item.userName }}</span>
            <span>{{ item.deptName }}</span>
            <span>
              <span>{{ item.totalAmount }}¥</span>
              <span>{{ item.orderCount }}</span>
            </span>
          </div>
        </div>
      </el-card>
      <el-card>
        <template #header>
          <div class="home_card_title">
            <span>审核排名</span>
          </div>
        </template>
        <div class="level_list">
          <div
            class="level_list_item"
            v-for="(item, index) in homeData?.auditOrderRank"
            :key="index"
          >
            <span
              :style="{
                background: getColor(index),
                color: index === 3 || index === 4 ? '#303133' : '#fff'
              }"
            >
              {{ index + 1 }}
            </span>

            <span>{{ item.userName }}</span>
            <span>{{ item.deptName }}</span>
            <span>
              <span>{{ item.totalAmount }}¥</span>
              <span>{{ item.orderCount }}</span>
            </span>
          </div>
        </div>
      </el-card>
    </div>

    <div class="home_dept_level">
      <el-card>
        <template #header>
          <div class="home_card_title">
            <span>分公司排名</span>
          </div>
        </template>
        <div class="level_list">
          <div class="level_list_item" v-for="(item, index) in homeData?.companyRank" :key="index">
            <span
              :style="{
                background: getColor(index),
                color: index === 3 || index === 4 ? '#303133' : '#fff'
              }"
            >
              {{ index + 1 }}
            </span>

            <span>{{ item.deptName }}</span>
            <span>
              <span>{{ item.totalAmount }}¥</span>
              <span>{{ item.orderCount }}</span>
            </span>
          </div>
        </div>
      </el-card>
      <el-card>
        <template #header>
          <div class="home_card_title">
            <span>部门排名</span>
          </div>
        </template>
        <div class="level_list">
          <div class="level_list_item" v-for="(item, index) in homeData?.deptRank" :key="index">
            <span
              :style="{
                background: getColor(index),
                color: index === 3 || index === 4 ? '#303133' : '#fff'
              }"
            >
              {{ index + 1 }}
            </span>
            <span>{{ item.deptName }}</span>
            <span>
              <span>{{ item.totalAmount }}¥</span>
              <span>{{ item.orderCount }}</span>
            </span>
          </div>
        </div>
      </el-card>
      <el-card>
        <template #header>
          <div class="home_card_title">
            <span>班组排名</span>
          </div>
        </template>
        <div class="level_list">
          <div class="level_list_item" v-for="(item, index) in homeData?.teamRank" :key="index">
            <span
              :style="{
                background: getColor(index),
                color: index === 3 || index === 4 ? '#303133' : '#fff'
              }"
            >
              {{ index + 1 }}
            </span>

            <span>{{ item.deptName }}</span>
            <span>
              <span>{{ item.totalAmount }}¥</span>
              <span>{{ item.orderCount }}</span>
            </span>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { getHome, GetHomeRes } from '@/api/home'
import { useDeptList } from '@/hooks/useDeptList'
import { useUserStore } from '@/store/modules/user'
import dayjs from 'dayjs'
import { simpleListUser } from '@/api/order/create'
import { dateFormatter } from '@/utils/formatTime'
import { usePermissions } from '@/hooks/useReadTeam'
import { defaultTime, getFormatTime } from '@/utils'

const userStore = useUserStore()
const userId = userStore.user.id
const homeData = ref<GetHomeRes>()
const userList = ref<{ label: string; value: number }[]>([])
const hasPermissions = usePermissions('bms:home:team')

const simpleListUserFn = async (deptId: string) => {
  try {
    if (!deptId) {
      return
    }
    const res = await simpleListUser({ deptId })
    userList.value = res.map((item) => {
      return {
        label: item.nickname,
        value: item.id
      }
    })
  } catch (e) {
    console.error(e)
  }
}

const formData = reactive({
  dateRange: [
    dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss')
  ],
  userId: '',
  deptId: '',
  tab: '0'
})
const constantcascaderProps = {
  value: 'id', // 数据中代表 value 的字段
  label: 'name', // 数据中代表 label 的字段
  children: 'children' // 数据中代表子节点的字段
}
let intervalId
watch(
  () => formData,
  (newVal) => {
    let data: { dateRange: string[]; userId?: number; deptId?: string } = { dateRange: [] }
    if (data.deptId === '') {
      simpleListUserFn(data.deptId)
    }
    if (newVal.tab === '1') {
      data = {
        deptId: newVal.deptId[newVal.deptId.length - 1] || '',
        dateRange: formData.dateRange
      }
    } else {
      data = {
        userId,
        dateRange: formData.dateRange
      }
    }
    getHomeFn(data)
  },
  { deep: true } // 深度监听
)

onMounted(() => {
  function getData() {
    let data: { dateRange: string[]; userId?: number; deptId?: string } = { dateRange: [] }
    if (formData.tab === '1') {
      data = {
        deptId: formData.deptId[formData.deptId.length - 1] || '',
        dateRange: formData.dateRange
      }
    } else {
      data = {
        userId,
        dateRange: formData.dateRange
      }
    }
    getHomeFn(data)
  }
  getData()
  intervalId = setInterval(getData, 60000)
})

onUnmounted(() => {
  clearInterval(intervalId)
})
const { deptList } = useDeptList()

const getColor = (index) => {
  switch (index) {
    case 0:
      return '#f68c1d'
    case 1:
      return '#3a8ee6'
    case 2:
      return '#3a8ee6'
    default:
      return '#eee'
  }
}
const getHomeFn = async (params: { dateRange: string[]; userId?: number; deptId?: string }) => {
  try {
    const res = await getHome({ ...params, dateRange: getFormatTime(params.dateRange) })
    homeData.value = res
  } catch (e) {
    console.error(e)
  }
}
</script>

<style lang="scss" scoped>
.home_filter_content {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}
.form_container {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  gap: 20px; /* 设置子元素间距 */
}
.home_bg {
  flex: 1;
  width: 100%;
  height: calc(100vh - 190px);
  background-image: url('/src/assets/imgs/login/bg.png'); /* 替换为你的背景图片路径 */
  background-size: cover; /* 确保背景图片始终覆盖整个页面 */
  background-position: center; /* 图片居中显示 */
  background-repeat: no-repeat; /* 禁止重复 */
  position: relative;
  .home_bg_img {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
  .home_bg_imgTwo {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
  .home_bg_title {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    font-family: FZShuTi;
    font-size: 280px;
    font-weight: 400;
    color: #fff;
  }
  .home_bg_titleTwo {
    width: 1400px;
    position: absolute;
    left: 50%;
    top: 68%;
    transform: translateX(-50%);
    font-family: STXinwei;
    font-size: 96px;
    font-weight: 400;
    color: #fff;
  }
}

::v-deep(.el-card) {
  height: 100%;
  .el-card__body {
    height: 100%;
  }
}
.home_card_title {
  font-size: 20px;
  color: #060505;
  font-weight: bold;
}
.level_list {
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow-y: auto;
  .level_list_item {
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-around;
    & > span:first-child {
      width: 25px;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      color: #fff;
      font-size: 14px;
    }
    & > span:nth-child(2) {
      flex: 1;
      padding: 0 25px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    & > span:last-child {
      width: 100px;
      display: flex;
      gap: 8px;
      justify-content: space-between;
    }
  }
}

.home_price {
  margin-top: 10px;
  display: flex;
  flex-direction: row;
  align-items: center;
  height: 160px;
  gap: 24px;
  & > div {
    flex: 1;
  }
  .home_price_item {
    height: 100%;
    display: flex;
    flex-direction: column;
    & > div:first-child {
      align-self: flex-end;
    }
    & > div:last-child {
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-around;
      .home_price_item_price {
        color: #000000;
        font-size: 35px;
        display: flex;
        flex-direction: row;
        align-items: center;
        gap: 10px;
        font-weight: 400;
      }
      .home_price_item_name {
        color: #4d4e50;
        font-size: 16px;
        display: flex;
        flex-direction: row;
        align-items: center;
      }
    }
  }
}

.home_status {
  margin-top: 10px;
  display: flex;
  gap: 24px;
  height: 187px;
  & > div {
    flex: 1;
  }
  .home_status_item {
    padding: 20px;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 15px;
    & > img {
      width: 40px;
    }
  }
}

.home_status_level {
  display: flex;
  flex-direction: row;
  align-items: center;
  height: 300px;
  margin-top: 10px;
  gap: 20px;
  & > div {
    flex: 1;
  }
}

.home_dept_level {
  margin-top: 10px;
  display: flex;
  gap: 24px;
  flex-direction: row;
  align-items: center;
  height: 300px;
  & > div {
    flex: 1;
  }
}
</style>
